﻿using System;
using System.Threading;
using System.Windows;
using Columbus.Controls;

namespace Columbus.ActionResults
{
    public class MessageBoxActionResult : ActionResult
    {
        private readonly string messageBoxText;
        private readonly string caption;
        private readonly MessageBoxButton? button;
        private readonly Action<MessageBoxResult> resultCallback;
        private readonly Frame navigationFrame;
        private MessageBoxResult result;

        public MessageBoxActionResult(NavigationContext context, string messageBoxText) : base(context)
        {
            navigationFrame = context.Navigator.NavigationFrame;
            this.messageBoxText = messageBoxText;
        }

        public MessageBoxActionResult(NavigationContext context, string messageBoxText, string caption, MessageBoxButton button) 
            : base(context)
        {
            navigationFrame = context.Navigator.NavigationFrame;
            this.messageBoxText = messageBoxText;
            this.caption = caption;
            this.button = button;
        }

        public MessageBoxActionResult(
            NavigationContext context, 
            string messageBoxText, 
            string caption, 
            MessageBoxButton button,
            Action<MessageBoxResult> resultCallback)
            : base(context)
        {
            navigationFrame = context.Navigator.NavigationFrame;
            this.messageBoxText = messageBoxText;
            this.caption = caption;
            this.button = button;
            this.resultCallback = resultCallback;
        }

        protected override void ExecuteInternal()
        {
            Dispatcher.Dispatch(() => navigationFrame.IsContentEnabled = true);
            var sync = new ManualResetEvent(false);
            Dispatcher.Dispatch(() =>
                                  {
                                      if (caption == null || button == null)
                                          MessageBox.Show(messageBoxText);
                                      else
                                          result = MessageBox.Show(messageBoxText, caption, button.Value);
                                      sync.Set();
                                  });
            sync.WaitOne();

            if (resultCallback != null)
                resultCallback(result);
        }
    }
}